<?php

class Index extends Controller {

	public function run() {
		$pluginVers = $this->_getPluginVers();
		$from = !empty($_GET['from']) ? $_GET['from'] : '';
		switch ($from) {
			case 'discuz':
				$this->_discuz($pluginVers);
				break;
			default;
				$this->_default($pluginVers);
				break;
		}
	}

	private function _default($pluginVers) {
		$config = Sdk\lib\Config::GetRoot();

		$var = array(
			'witUrl' => WitURL,
			'pluginVers' => $pluginVers,
			'pluginInfo' => Sdk\lib\Core::GetInfo($pluginVers),
			'witPid' => !empty($config['base']['witPid']) ? $config['base']['witPid'] : 0,
		);
		$this->template('index', $var);
	}

	private function _discuz($pluginVers) {
		$ret = array();
		$infos = Sdk\lib\Core::GetInfo($pluginVers);
		$host = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];
		foreach ($pluginVers as $identifier => $branchs) {
			foreach ($branchs as $branch) {
				if(empty($branch['isDiscuz'])) {
					continue;
				}
				$_row = array();
				$_row['path'] = $identifier . '/' . $branch['ver'];
				$_row['appUrl'] = $host . Common::getURI('/');
				$_row['appName'] = !empty($infos[$identifier]['name']) ? $infos[$identifier]['name'] : $identifier . ' ' . $branch['ver'];
				$_row['appIcon'] = !empty($infos[$identifier]['icon']) ? $infos[$identifier]['icon'] : 'https://static.witframe.com/assets/images/wit_ico.png';
				$_row['branchName'] = !empty($infos[$identifier]['branch'][$branch['ver']]) ? $infos[$identifier]['branch'][$branch['ver']] : $branch['ver'];
				$_row['sellerName'] = 'SDK';
				$ret[] = $_row;
			}
		}
		$this->successMessage('', $ret);
	}

	private function _getPluginVers() {
		$pluginRoot = ROOT_PATH . '/www/';

		$plugins = array();
		$f = opendir($pluginRoot);
		while (($plugin = readdir($f)) !== false) {
			if(substr($plugin, 0, 1) == '.') {
				continue;
			}
			$pluginDir = $pluginRoot . '/' . $plugin;
			if(!is_dir($pluginDir)) {
				continue;
			}
			$fsub = opendir($pluginDir);
			$vers = array();
			while (($ver = readdir($fsub)) !== false) {
				if(substr($ver, 0, 1) == '.') {
					continue;
				}
				$verDir = $pluginDir . '/' . $ver;
				if(!is_dir($verDir)) {
					continue;
				}
				$bType = is_dir($pluginDir . '/' . $ver . '/controllers') ? 1 : 2;
				if(file_exists($pluginDir . '/' . $ver . '/conf/wechatMini.yaml')) {
					$bType = 3;
				}
				$isDiscuz = file_exists($pluginDir . '/' . $ver . '/controllers/Discuz/Config.php');
				$vers[] = array(
					'ver' => $ver,
					'bType' => $bType,
					'isDiscuz' => $isDiscuz,
				);
			}
			closedir($fsub);
			$plugins[$plugin] = $vers;
		}
		closedir($f);
		return $plugins;
	}
}